/*
 * guiWrapper.cpp
 *
 *  Created on: Mar 8, 2011
 *      Author: B. Jones
 */


#include "guiWrapper.h"
#include "pthread.h"
#include <sstream>
#include <iostream>
#include <QScrollBar>
#include <QFileDialog>
#include <QFileInfo>
#include <QDialog>
#include <QTimer>
#include <incomingFileForm.h>

std::queue<eventStore> listener::eventQueue;
pthread_mutex_t listener::mutex = PTHREAD_MUTEX_INITIALIZER;

guiWrapper::guiWrapper()
{
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(processComEvents()));
	timer->start(20);

}


void
guiWrapper::processComEvents()
{

	pthread_mutex_lock(&listener::mutex);
	if(listener::eventQueue.size()>0)
	{
		//for(int e = 0;e<listener::eventQueue.size();e++)
		{
		int type = listener::eventQueue.front().type;
		std::string tag(listener::eventQueue.front().tag);
		std::string str(listener::eventQueue.front().message);
		double value = listener::eventQueue.front().amount;
		std::string extra(listener::eventQueue.front().extra);

		listener::eventQueue.pop();


		if(type<4||type==7)
		{
			std::stringstream comp("");
			std::string colour;
			// change colour of message depending on event type code
			if(type==3||type==7)colour="gray"; // status message
			else if(type==2)colour="blue"; // other user
			else if(type==1)colour="red"; // you
			// nice thing about this is that text in Qt can be rendered using html
			comp<<"<font color=\""<<colour<<"\"><b>"<<tag<<"</b>: "<<str<<"</font>\n"<<std::endl;

			uiEncap::ui->chatWindow->append(QString(comp.str().c_str()));
			//uiEncap::ui->chatWindow->append(QString("\n"));
			uiEncap::ui->scrollArea->verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMaximum);

			if(type==1&&type!=7)
			{
				coms->sendMessage(str);
			}
			if(type==7) // new peer
			{
				uiEncap::ui->peerList->addItem(QString(extra.c_str()));
			}

		}
		else if(type==4) // connected peer trying to send file
		{
			std::stringstream comp("");
			comp<<"<font color=\""<<"gray"<<"\"><b>"<<"STATUS"<<"</b>: "<<"Peer wants to send file "<<str<<"</font>\n"<<std::endl;
			uiEncap::ui->chatWindow->append(QString(comp.str().c_str()));
			//uiEncap::ui->chatWindow->append(QString("\n"));
			uiEncap::ui->scrollArea->verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMaximum);
			comp.str("");
			comp<<"<font color=\""<<"gray"<<"\"><b>"<<"STATUS"<<"</b>: "<<"Please press Accept button if accept "<<"</font>\n"<<std::endl;
			uiEncap::ui->chatWindow->append(QString(comp.str().c_str()));
			uiEncap::ui->scrollArea->verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMaximum);

			qd = new QDialog(uiEncap::ui->centralwidget);
			Ui_IncomingFileDialog ifd;
			ifd.setupUi(qd);
			ifd.incomingFileString->setText(str.c_str());
			qd->show();

			if(qd->exec()==QDialog::Accepted)
			{
				initiateFileSend(str,true);
			}
			else
			{
				initiateFileSend("",false);
			}
		}
		else if(type==5) // send bar update
		{
			//std::cout<<value<<std::endl;
			uiEncap::ui->fileSendProgress->setValue(value);
		}
		else if(type==6) // receive bar update
		{
			//std::cout<<value<<std::endl;
			uiEncap::ui->fileReceiveProgress->setValue(value);
		}
		}
	}
	pthread_mutex_unlock(&listener::mutex);

}

void
guiWrapper::initiateFileSend(std::string fname,bool yes)
{
	if(yes)
	{
		QFileDialog fileDialog(uiEncap::ui->centralwidget,QString(fname.c_str()));
		fileDialog.setAcceptMode(QFileDialog::AcceptSave);
		//if(fileDialog.exec()==QDialog::Accepted)
		{
			QString saveName=fileDialog.getSaveFileName();
			coms->doFileReceive(saveName.toStdString().c_str(),true);
		}
		//else
		{
			//coms->doFileReceive("./",false);
		}
	}
	else
	{
		coms->doFileReceive("./",false);
	}
}

void
guiWrapper::serverButtonClicked()
{
	mode = 0;
	handleParams();

}

void
guiWrapper::serverFormOk()
{
	if(mode==0)coms = new server();
	else if(mode==1)coms = new client();
	coms->initiateChannelManager();

	std::string charNick;

	if(mode==0)
	{
		coms->startServerThread(atoi(sd->portField->text().toStdString().c_str()));
		charNick.assign(sd->userField->text().toStdString());
		coms->charNick.assign(charNick);
		paramsWidget->close();
		delete sd;
		uiEncap::ui->serverStartButton->setStyleSheet(
								 "border-style: outset;"
								 "border-width: 5px;"
								 "border-color: red;"
		);
	}
	else if(mode==1)
	{
		std::string serverString(cd->serverField->text().toStdString());
		coms->startClientThread(serverString.c_str(),atoi(cd->portField->text().toStdString().c_str()));
		charNick.assign(cd->userField->text().toStdString());
		coms->charNick.assign(charNick);
		paramsWidget->close();
		delete cd;
		uiEncap::ui->connectButton->setStyleSheet(
								 "border-style: outset;"
								 "border-width: 5px;"
								 "border-color: red;"
		);
	}
	delete paramsWidget;

	uiEncap::ui->connectButton->setEnabled(false);
	uiEncap::ui->serverStartButton->setEnabled(false);
	uiEncap::ui->chatInput->setEnabled(true);
	uiEncap::ui->sendButton->setEnabled(true);

	//coms->initiateChannelManager();
}

void
guiWrapper::handleParams()
{
	paramsWidget=new QDialog(uiEncap::ui->centralwidget);
	if(mode==1)
	{
		cd=new Ui_ClientDialog;
		cd->setupUi(paramsWidget);
		QObject::connect(cd->buttonBox, SIGNAL(accepted()), this, SLOT(serverFormOk()));
		//QObject::connect(buttonBox, SIGNAL(rejected()), ServerDialog, SLOT(reject()));


	}
	else if(mode==0)
	{
		sd=new Ui_ServerDialog;
		sd->setupUi(paramsWidget);
		QObject::connect(sd->buttonBox, SIGNAL(accepted()), this, SLOT(serverFormOk()));
		//QObject::connect(buttonBox, SIGNAL(rejected()), ServerDialog, SLOT(reject()));

	}
	paramsWidget->show();
}

void
guiWrapper::connectButtonClicked()
{
	mode=1;
	handleParams();
}

void
guiWrapper::sendButtonClicked()
{
	std::cout<<"Send file button clicked"<<std::endl;

	QFileDialog dialog(uiEncap::ui->centralwidget);
	//dialog.setFileMode(QFileDialog::AnyFile);
	dialog.setFileMode(QFileDialog::ExistingFiles);

	if(dialog.exec()== QDialog::Accepted)
	{
		QStringList filenames=dialog.selectedFiles();
		int upto = filenames.size();

		for(int f = 0;f<upto;f++)
		{
			 //std::string fname = filenames.at(f).toStdString();
			 QFileInfo fileinfo(filenames.at(f));
			 std::string fname = fileinfo.fileName().toStdString();
			 std::string absolutePath = fileinfo.absoluteFilePath().toStdString();
			 //std::cout<<fname<<std::endl;
			 coms->doFileTransfer(absolutePath.c_str(),fname.c_str());
			 //coms->cm->initiateFileTransfer(int sockFile_send, const char* filePath, const char* filename)
		}
	}


}

void
guiWrapper::syncButtonClicked()
{

}

